package cn.ctodb.wxmp.web.rest;

import cn.ctodb.wxmp.service.MpService;
import cn.ctodb.wxmp.service.dto.MpDTO;
import com.codahale.metrics.annotation.Timed;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

import javax.inject.Inject;

/**
 * Created by cc on 2017/1/4.
 */
@RestController
public class ApiResource {

    private final Logger log = LoggerFactory.getLogger(ApiResource.class);

    @Inject
    private MpService mpService;

    @Inject
    private SpringTemplateEngine templateEngine;

    @GetMapping("/receive/{id}")
    @Timed
    public String check(@PathVariable Long id, @RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {
        MpDTO mp = mpService.findOne(id);
        boolean v = mpService.verifyUrl(mp.getToken(), signature, timestamp, nonce);
        if (v) {
            return echostr;
        }
        return "success";
    }

    @PostMapping("/receive/{id}")
    @Timed
    public String receive(@PathVariable Long id, @RequestBody String body) {
        Context context = new Context();
        try {
            Document document = DocumentHelper.parseText(body);
            Element xml = document.getRootElement();
            Element MsgType = xml.element("MsgType");
            Element FromUserName = xml.element("FromUserName");
            Element ToUserName = xml.element("ToUserName");
            if ("text".equals(MsgType.getText())) {
                Element Content = xml.element("Content");
                log.debug(FromUserName.getText() + ":" + Content.getText());
            }
            context.setVariable("toUser",FromUserName.getText());
            context.setVariable("fromUser",ToUserName.getText());
            context.setVariable("content","content");
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return templateEngine.process("msg.text", context);
    }

}
